package com.gsj.system.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gsj.common.pojo.R;
import com.gsj.common.utils.JwtUtils;
import com.gsj.system.config.MybatiesConfig;
import com.gsj.system.config.RsaKeyProperties;
import com.gsj.system.eneity.Role;
import com.gsj.system.eneity.User;
import com.gsj.system.mapper.UserMapper;
import com.gsj.system.pojo.LoginVo;
import com.gsj.system.pojo.UserVo;
import com.gsj.system.pojo.UserVoSecond;
import com.gsj.system.pojo.UserVoThird;
import com.gsj.system.service.UserService;
import com.gsj.system.utils.SystemTimeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.util.List;

/**
 * @program: clms-eighth
 * @description: 用户服务处的实现类
 * @author: 刘守霖
 * @create: 2021-07-16 18:35
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MybatiesConfig mybatiesConfig;
    @Resource
    private RsaKeyProperties rsaKeyProperties;
    @Override
    public R findByName(LoginVo loginVo) {
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //调用login方法
        UsernamePasswordToken usernameToken = new UsernamePasswordToken(loginVo.getUsername(), loginVo.getPassword());
        try{
            subject.login(usernameToken);
        }
        catch (UnknownAccountException e){
            System.out.println("用户名不对！！！！");
            R.error();
        }catch (IncorrectCredentialsException credentialsException){
            System.out.println("密码不对！！！");
            R.error();
        }
        User u =(User)subject.getPrincipal();
        System.out.println(u);
        User user = new User();
        user.setUserId(u.getUserId());
        user.setStatus(u.getStatus());
        user.setDeptId(u.getDeptId());
        user.setAvatar(u.getAvatar());
        user.setUserName(loginVo.getUsername());
        String token = JwtUtils.generateTokenExpireInMinutes(user,rsaKeyProperties.getPrivateKey(),24 * 60);


        return R.ok().put("token",token);
    }

    @Override
    public R  queryAllUser(Integer currentPage, Integer pageSize, UserVo uservo) {
        Page<User> userPage = new Page<>(currentPage, pageSize);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(uservo.getUserName())){
            userQueryWrapper.like("user_name",uservo.getUserName());
        }
        if(StringUtils.isNotEmpty(uservo.getLoginName())) {
            userQueryWrapper.like("login_name", uservo.getLoginName());
        }
        if(StringUtils.isNotEmpty(uservo.getPhonenumber())) {
            userQueryWrapper.like("phonenumber", uservo.getPhonenumber());
        }
        if(StringUtils.isNotEmpty(uservo.getEmail())) {
            userQueryWrapper.like("email", uservo.getEmail());
        }

        Page<User> userPage1 = userMapper.selectPage(userPage, userQueryWrapper);
        System.out.println(userPage1.getTotal());
        return R.ok().put("records",userPage1.getRecords()).put("total",userPage1.getTotal());
    }

    @Override
    public R addUser(UserVoThird userVo,String username) {
        List<User> users = userMapper.queryallUser();
        for(User user:users){
            if(user.getUserName().equals(userVo.getUserName())){
                return R.ok().put("message","用户名重复");
            }
            if(user.getEmail().equals(userVo.getEmail())){
                return R.ok().put("message","邮箱重复");
            }
            if(user.getPhonenumber().equals(userVo.getPhonenumber())){
                return R.ok().put("message","手机号码重复");
            }
        }
        userVo.setCreateTime(SystemTimeUtil.getTime());
        userMapper.addUser(userVo,username);
        return R.ok().put("message","新增成功");
    }

    @Override
    public R querybyUserid(Integer userId) {
        List<User> users = userMapper.querybyUserid(userId);
        return  R.ok().put("users",users);
    }

    @Override
    public R editUser(UserVo userVo,String username) {
        userVo.setUpdateTime(SystemTimeUtil.getTime());
        String userName = userVo.getUserName();
        Integer userId = userVo.getUserId();
        List<User> users = userMapper.querybyUserid(userId);
        String userName1 = users.get(0).getUserName();
        if(userName.equals(userName1)){
            userMapper.updatebyUserid(userVo,username);
            return R.ok().put("message","修改成功");
        }
        String email = userVo.getEmail();
        String email1 = users.get(0).getEmail();
        if(email.equals(email1)){
            userMapper.updatebyUserid(userVo,username);
            return R.ok().put("message","修改成功");
        }
        String phonenumber = userVo.getPhonenumber();
        String phonenumber1 = users.get(0).getPhonenumber();
        if(phonenumber.equals(phonenumber1)){
            userMapper.updatebyUserid(userVo,username);
            return R.ok().put("message","修改成功");
        }
        List<User> users1 = userMapper.queryallUser();
        for(User user:users1){
            if(user.getUserName().equals(userName)){
                return R.ok().put("message","用户名已存在，请重新修改");
            }
            if(user.getPhonenumber().equals(phonenumber)){
                return R.ok().put("message","邮箱已存在，请重新修改");
            }
            if(user.getEmail().equals(email)){
                return R.ok().put("message","手机号码已存在，请重新修改");
            }
        }

        userMapper.updatebyUserid(userVo,username);
        return R.ok().put("message","修改成功");
    }

    @Override
    public R deleteUserBYid(Integer userId) {
        userMapper.deleteByUserid(userId);
        return null;
    }

    @Override
    public R editUserStatus(Integer id,Integer status) {
        userMapper.editUserStatus(id,status);
        return null;
    }

    @Override
    public R editPassword(UserVoSecond userVoSecond) {
        String p = userVoSecond.getPassword();
        String userName = userVoSecond.getUserName();
        Md5Hash md5Hash = new Md5Hash(p, "efdd1d36-2430-4", 1024);
        String password = md5Hash.toString();
        System.out.println(md5Hash);
        userMapper.editPassword(userName,password);
        return null;
    }


}
